package com.example.work4.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.NetworkInfo
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.work4.DataUtil
import com.example.work4.FriendActivity
import com.example.work4.LoginActivity
import com.example.work4.R
import com.example.work4.adapter.ChatListAdapter
import com.example.work4.common.FIN
import com.example.work4.common.ImageUtil
import com.example.work4.data.MyObServerable
import com.example.work4.http.FriendRetrofitImp
import com.example.work4.http.MessageRetrofitImp
import com.example.work4.http.data.FriendList
import com.example.work4.http.data.MomentPageData
import com.example.work4.po.ResultBean
import com.example.work4.po.SSOInfo
import com.farsunset.cim.sdk.android.CIMEventListener
import com.farsunset.cim.sdk.android.CIMListenerManager
import com.farsunset.cim.sdk.android.CIMPushManager
import com.farsunset.cim.sdk.android.model.Message
import com.farsunset.cim.sdk.android.model.ReplyBody
import com.farsunset.cim.sdk.android.model.SentBody
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.disposables.Disposable
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [BlankFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class BlankFragment : Fragment() ,View.OnClickListener, CIMEventListener {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null
    var layout: ConstraintLayout?=null
    val adapter = ChatListAdapter()
    var messageServiceImp = context?.let { MessageRetrofitImp(it) }
    var recyclerView:RecyclerView?= null
    var imageUtil:ImageUtil? = null
    var friendRetro = FriendRetrofitImp()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
        CIMListenerManager.registerMessageListener(this);
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }

    var mHandler= @SuppressLint("HandlerLeak")
    object : Handler()
    {
        override fun handleMessage(msg: android.os.Message) {
            super.handleMessage(msg)
            when(msg.what)
            {
                DataUtil.UPDATE_MESSAGE_LIST->
                {
                    messageServiceImp!!.messageList(recyclerView!!,adapter)

                }
                DataUtil.UPDATE_FRIEND_LIST ->{

                }
            }
        }

    }

    override fun onClick(v: View?) {
        when(v?.id) {
            R.id.fan_layout ->{
                val intent = Intent(view?.context, FriendActivity::class.java)
                intent.putExtra("type","fan")
                startActivity(intent)
            }

            R.id.follow_layout->{
                val intent = Intent(view?.context, FriendActivity::class.java)
                intent.putExtra("type","follow")
                startActivity(intent)
            }

            R.id.friend_layout ->{
                val intent = Intent(view?.context, FriendActivity::class.java)
                intent.putExtra("type","friend")
                startActivity(intent)
            }
        }

    }


    override fun onResume() {
        super.onResume()
    }

    var fansNum:TextView? = null
    var followNum:TextView? = null
    var friendNum:TextView? = null

    private fun loadPersonalInfo() {
        view?.let {
            val name = it.findViewById<TextView>(R.id.m_nickname)
            name.text = SSOInfo.username
            val email = it.findViewById<TextView>(R.id.email)
            email.text = SSOInfo.email
            val imageView = it.findViewById<ImageView>(R.id.m_avatar)
            imageUtil!!.GlideLoadCenterCrop(SSOInfo.avatar!!, imageView!!)

            val fanLayout = it.findViewById<LinearLayout>(R.id.fan_layout)
            val followLayout = it.findViewById<LinearLayout>(R.id.follow_layout)
            val friendLayout = it.findViewById<LinearLayout>(R.id.friend_layout)
            fanLayout.setOnClickListener(this)
            followLayout.setOnClickListener(this)
            friendLayout.setOnClickListener(this)
            fansNum = it.findViewById<TextView>(R.id.fans_num)
            followNum = it.findViewById<TextView>(R.id.follow_num)
            friendNum = it.findViewById(R.id.friend_num)
            updateFriendsList()
        }
    }

    fun updateFriendsList(){
        friendRetro.listCall().enqueue(object : Callback<ResultBean<FriendList>>{
            override fun onResponse(call: Call<ResultBean<FriendList>>,
                                    response: Response<ResultBean<FriendList>>) {
                if(response.code()== 200){
                    val list: FriendList? = response.body()!!.data
                    fansNum!!.text = list!!.fanList.size.toString()
                    followNum!!.text = list.followList.size.toString()
                    friendNum!!.text = list.friendList.size.toString()
                }
            }
            override fun onFailure(call: Call<ResultBean<FriendList>>, t: Throwable) {
            }
        })
    }


    val observer: Observer<Int> = object:Observer<Int>{
        override fun onSubscribe(d: Disposable) {

        }
        override fun onNext(t: Int) {
                loadPersonalInfo()
        }
        override fun onError(e: Throwable) {

        }
        override fun onComplete() {

        }
    }


    private fun init() {
        imageUtil = ImageUtil(requireContext())
        DataUtil.messageHandler = mHandler
        MyObServerable.observer = observer
        messageServiceImp = context?.let { MessageRetrofitImp(it) }
        layout=view?.findViewById(R.id.con_userinfo)
        layout?.setOnClickListener(this)
        recyclerView = view?.findViewById(R.id.messageRecyclerView)!!
        recyclerView!!.layoutManager = LinearLayoutManager(requireContext())
        messageServiceImp!!.messageList(recyclerView!!,adapter)
        val isConnected = CIMPushManager.isConnected(context)
        Toast.makeText(context,isConnected.toString(),Toast.LENGTH_SHORT).show()
        loadPersonalInfo()
        CIMPushManager.bind(context, SSOInfo.id.toString())
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank, container, false)
    }



    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment BlankFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            BlankFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }

    /**********CIM接口*************/
    override fun onMessageReceived(p0: Message?) {
        messageServiceImp!!.messageList(recyclerView!!,adapter)
    }

    override fun onReplyReceived(p0: ReplyBody?) {

    }

    override fun onSendFinished(p0: SentBody?) {

    }

    override fun onNetworkChanged(p0: NetworkInfo?) {

    }

    override fun onConnectFinished(p0: Boolean) {


    }

    override fun onConnectionClosed() {

    }

    override fun onConnectFailed() {

    }

    override fun getEventDispatchOrder(): Int {
        return 2
    }

}